package jwtx

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

// 自定义JWT负载
type CustomClaims struct {
	UserID   uint64 `json:"user_id"`
	Username string `json:"username"`
	jwt.RegisteredClaims
}

// 生成JWT
func GenerateToken(userID uint64, username string) (string, error) {
	claims := CustomClaims{
		UserID:   userID,
		Username: username,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(2 * time.Hour)), // 设置过期时间为2小时
			Issuer:    "sso-idp",                                         // 签发者标识
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) // 使用RS256算法签名
	return token.SignedString(SignKey)
}

// 验证JWT
func VerifyToken(tokenString string) (*CustomClaims, error) {
	//fmt.Println("tokenString:", tokenString)
	token, err := jwt.ParseWithClaims(
		tokenString,
		&CustomClaims{},
		func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, errors.New("不支持的签名算法")
			} // 验证签名算法
			return VerifyKey, nil
		},
	)
	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid { // 验证令牌有效性并提取claims
		if claims.Issuer != "sso-idp" { // 验证签发者是否为信任的IdP
			return nil, errors.New("非法的签发者")
		}
		return claims, nil
	}

	return nil, errors.New("无效的令牌")
}
